package cn.iocoder.yudao.core.web.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;


@Configuration
@ConditionalOnProperty(value = "yudao.start.timeout",havingValue ="true" )
public class BeanInitCostTimeBeanPostProcessor implements BeanPostProcessor {

    private static final Logger logger = LoggerFactory.getLogger(BeanInitCostTimeBeanPostProcessor.class);

    private static final ConcurrentHashMap<String, Long> START_TIME = new ConcurrentHashMap<>();

    @Override
    public Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {
        START_TIME.put(beanName, System.currentTimeMillis());
        return bean;
    }
    @Override
    public Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {
     if(Objects.nonNull(START_TIME.get(beanName))){
         long costTime = System.currentTimeMillis() - START_TIME.get(beanName);
          if(costTime>50) {
              logger.warn("初始化bean耗时严重 bean:{},cost:{}",bean.getClass().getSimpleName(),costTime);
          }
     }
        START_TIME.clear();
        return bean;
    }

}
